import { defineStore } from 'pinia'
import request from '@/request/request'

export const useArticleStore = defineStore('article', {
  state: () => ({
    articles: [],
    isAllArticles: false
  }),
  
  actions: {
    // 获取当前用户的文章
    async fetchUserArticles() {
      try {
        const res = await request.get('/WanZhang')
        if (res.code === 200) {
          this.articles = res.data
          this.isAllArticles = false
        } else {
          this.articles = []
          throw new Error(res.message || '获取文章失败')
        }
      } catch (e) {
        this.articles = []
        throw e
      }
    },
    
    // 获取所有用户的文章
    async fetchAllArticles() {
      try {
        const res = await request.get('/WanZhang/all')
        if (res.code === 200) {
          this.articles = res.data
          this.isAllArticles = true
        } else {
          this.articles = []
          throw new Error(res.message || '获取文章失败')
        }
      } catch (e) {
        this.articles = []
        throw e
      }
    },

    async updateArticle(index, newData) {
      try {
        const res = await request.put(`/WanZhang/${newData.id}`, newData)
        if (res.code === 200) {
          this.articles[index] = { ...newData }
        } else {
          throw new Error(res.message || '更新文章失败')
        }
      } catch (e) {
        throw e
      }
    },

    async deleteArticle(id) {
      try {
        const res = await request.delete(`/WanZhang/${id}`)
        if (res.code === 200) {
          this.articles = this.articles.filter(item => item.id !== id)
        } else {
          throw new Error(res.message || '删除文章失败')
        }
      } catch (e) {
        throw e
      }
    }
  }
}) 